<template>
	<view>
		<view class="home-header">
			<view @click="jumpPage('/subPackages/city/city')">
				<uni-icons type="location" size="28"></uni-icons>
				<text class="header-text" >{{currentCity}}</text>
			</view>
			<view @click="jumpPage('/subPackages/map/map')">
				<uni-icons type="map" size="28"></uni-icons>
				<text class="header-text">地图</text>
			</view>
			<view @click="jumpPage('/subPackages/search/search')">
				<uni-icons type="search" size="28"></uni-icons>
				<text class="header-text">搜索</text>
			</view>
		</view>
		<view class="content">
			<view>
				<view class="waterfall-box h-flex-x h-flex-2">
					<view>
						<helang-waterfall 
							v-for="(item,index) in leftList" 
							:key="index" 
							:params="item" 
							tag="left"
							:index="index"
							@height="onHeight"
							@click="onClick"
						></helang-waterfall>
					</view>
					<view>
						<helang-waterfall 
							v-for="(item,index) in rightList" 
							:key="index" 
							:params="item" 
							@height="onHeight"
							@click="onClick"
							tag="right"
							:index="index"
						></helang-waterfall>
					</view>
				</view>
				<view class="load-txt">{{ajax.loadTxt}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import helangWaterfall from "@/uni_modules/helang-waterfall/components/helang-waterfall/helang-waterfall"
	export default {
		components:{helangWaterfall},
		data() {
			return {
				adCode:null,
				currentCity:null,
				list:[],
				leftHeight: 0,
				rightHeight: 0,
				leftList: [],
				rightList: [],
				ajax: {
					// 是否可以加载
					load: true,
					// 加载中提示文字
					loadTxt: '',
					// 每页的请求条件
					rows:10,
					// 页码
					page:1,
				}
			}
		},
		onLoad(){
			this.checkLogin()
		},
		onShow(){				
			this.currentCity=this.$store.state.adName || '城市'
			setTimeout(()=>{
				this.currentCity=this.$store.state.adName || '城市'
				this.adCode=this.$store.state.adCode
				this.getList()
			},1000)
		},
		// 触底触发
		// onReachBottom() {
		// 	this.getList();
		// },
		// 下拉刷新
		onPullDownRefresh(){
			this.getList()
			// 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
			// setTimeout(()=>{
			// 	this.ajax.page = 1;
			// 	this.leftHeight = 0;
			// 	this.rightHeight = 0;
			// 	this.ajax.load = true;
			// 	this.getList();
			// },800);
		},
		methods: {
			// 检查登录
			checkLogin(){
				uni.request({
					url:getApp().globalData.URL+'/user/checkRegister?openid='+getApp().globalData.openid,
					method:'post',
					header: {
					    'Content-Type': 'application/x-www-form-urlencoded'  
				    },
					success:(res)=>{
						if(res.errMsg==="request:ok"){
							if(res.data===1){
								let session
								uni.showLoading({
									title:'登录中',
									success:()=>{
										uni.login({
											success:(res)=>{
												if(res.errMsg==='login:ok'){
													let code=res.code
													uni.request({
														url:'https://yuayu.top/user/login',
														method:'post',
														data:{
															code:code
														},
														header:{
															'Content-Type': 'application/x-www-form-urlencoded'  
														},
														success:(res)=>{
															session=res.data.session_key,
															uni.setStorage({
																key:'session',
																data:session,
																success:()=>{
																	uni.hideLoading()
																}
															})
														}
													})
												}
											}
										})
									}
								})
							}
						}
					}
				})
			},
			// 页面跳转
			jumpPage(path){
				uni.navigateTo({
					url:path
				})
			},
			// 瀑布流
			// 监听高度变化
			onHeight(height, tag) {
				if (tag == 'left') {
					this.leftHeight += height;
				} else {
					this.rightHeight += height;
				}
			},
			// 组件点击事件
			onClick(index, tag){
				let selectedItem
				if(tag == 'left'){
					selectedItem=this.leftList[index];
				}else{
					selectedItem=this.rightList[index];
				}
				uni.navigateTo({
					url:'/subPackages/list-item/list-item?id='+selectedItem.id
				})
				// 对应的数据
				// let direction = {
				// 	"left":'左',
				// 	"right":'右'
				// }
				// uni.showToast({
				// 	title:`${direction[tag]}侧列表第${index+1}个被点击`,
				// 	icon:'none'
				// })
			},
			// 获取数据
			async getList() {
				if (!this.ajax.load) {
					return
				}
				// this.ajax.load = false;
				// this.ajax.loadTxt = '加载中';
				uni.request({
					url:getApp().globalData.URL+'/message/getCityMessages?city='+this.adCode,
					method:'POST',
					header:{
						'Content-Type': 'application/x-www-form-urlencoded'  
					},
					success:(res)=>{
						this.list = res.data.List
						this.addList(this.list)
					},
					fail: (e) => {
						uni.showToast({
							title:'获取失败！'
						})
					},
					complete:()=>{
						uni.hideLoading()
					}
				})
			},
			addList(res) {
				// 获取到的数据，请注意数据结构
				
				if(!res || res.length < 1){
					this.leftList= []
					this.rightList= []
					this.ajax.loadTxt = '没有更多了';
					return;
				}
				// 左右列表高度的差
				let differ = this.leftHeight - this.rightHeight;
				// 计算差值，用于确定优先插入那一边
				let differVal = 0;
								
				// 初始化左右列表的数据
				let i = differ > 0 ? 1 : 0;
				
				let [left, right] = [
					[],
					[]
				];
				
				
				// 获取插入的方向
				let getDirection = (index)=>{
					/* 左侧高度大于右侧超过 600px 时，则前3条数据都插入到右边 */
					if(differ>= 600 && index < 3){
						differVal = 1;
						return 'right';
					}
					
					/* 右侧高度大于左侧超过 600px 时，则前3条数据都插入到左边 */
					if(differ <= -600 && index < 3){
						differVal = -1;
						return 'left';
					}
					
					/* 左侧高度大于右侧超过 350px 时，则前2条数据都插入到右边 */
					if(differ >= 350 && index < 2){
						return 'right';
					}
					/* 右侧高度大于左侧超过 350px 时，则前2条数据都插入到左边 */
					if(differ <= -350 && index < 2){
						differVal = -1;
						return 'left';
					}
					
					/* 当前数据序号为偶数时，则插入到左边 */
					if ((i+differVal) % 2 == 0) {
						return 'left';
					} else {
						/* 当前数据序号为奇数时，则插入到右边 */
						return 'right';
					}
				}
				
				// 将数据源分为左右两个列表，容错差值请自行根据项目中的数据情况调节
				res.forEach((item, index) => {
					if(getDirection(index) == 'left'){
						//console.log(`差值：${differ},方向：left，序号${index}`)
						left.push(item);
					}else{
						//console.log(`差值：${differ},方向：right，序号${index}`)
						right.push(item);
					}
					i++;
				});
				this.$nextTick(() => {
					this.leftList = left;
					this.rightList = right;
					// if (this.ajax.page == 1) {
					// 	this.leftList = left;
					// 	this.rightList = right;
					// 	// uni.stopPullDownRefresh();
					// } else {
					// 	this.leftList = [...this.leftList, ...left];
					// 	this.rightList = [...this.rightList, ...right];
					// }
				})
				// 将左右列表的数据插入，第一页时则覆盖
				// if(this.ajax.page == 1){
				// 	this.leftList = left;
				// 	this.rightList = right;
				// 	uni.stopPullDownRefresh();
				// }else{
				// 	this.leftList = [...this.leftList, ...left];
				// 	this.rightList = [...this.rightList, ...right];
				// }
			
				this.ajax.load = true;
				// this.ajax.loadTxt = '上拉加载更多';
				this.ajax.page++;
			}
		},
	}
</script>

<style lang="scss" scoped>
.home-header{
	margin-top: 30rpx;
	display: flex;
	justify-content: space-around;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid rgba(0,0,0,.3);
	view{
		flex: 1;
		text-align: center;
		display:flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		image{
			width: 45rpx;
			height: 45rpx;
			margin-right: 10rpx;
		}
	}
}
.waterfall-box {
		padding: 20rpx 10rpx;
		box-sizing: border-box;

		>view {
			padding: 0 10rpx;
		}
	}

	.h-flex-x {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;

		&.h-flex-2 {
			>view {
				width: 50%;
			}
		}
	}
	
	.load-txt{
		padding: 0 0 20rpx 0;
		text-align: center;
		color: #999;
		font-size: 24rpx;
	}
</style>
